#include "cachelistmanager.h"

#include <QClipboard>
#include <QMouseEvent>

CacheListManager::CacheListManager(Ui::Index *ui,QObject *parent)
    : QObject{parent}
{
    this->ui = ui;
    ui->tableWidget_cacheList_cacheList->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->tableWidget_cacheList_cacheList->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->tableWidget_cacheList_cacheList->verticalHeader()->hide();
    ui->tableWidget_cacheList_keyNameList->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->tableWidget_cacheList_keyNameList->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->tableWidget_cacheList_keyNameList->verticalHeader()->hide();

    init();

    ui->tableWidget_cacheList_cacheList->viewport()->installEventFilter(this);
    ui->tableWidget_cacheList_keyNameList->viewport()->installEventFilter(this);
    connect(ui->tableWidget_cacheList_cacheList,&QTableWidget::itemClicked,this,[=](QTableWidgetItem *item){
        int row = item->row();
        cacheName = ui->tableWidget_cacheList_cacheList->item(row,1)->text();
        initKeyListTable(cacheName);
    });
    connect(ui->tableWidget_cacheList_keyNameList,&QTableWidget::itemClicked,this,[=](QTableWidgetItem *item){
        int row = item->row();
        QString cacheKeyName = ui->tableWidget_cacheList_keyNameList->item(row,1)->text();
        if(cacheKeyName != "暂无数据"){
            initCacheContent(cacheName,cacheKeyName);
        }
    });
    connect(ui->btn_caccheListRefresh,&QPushButton::clicked,this,[=](){
        init();
    });
    connect(ui->btn_keyNameListRefresh,&QPushButton::clicked,this,[=](){
        initKeyListTable(cacheName);
    });
    connect(ui->btn_cacheclearAll,&QPushButton::clicked,this,[=](){
        int flag = QMessageBox::question(0,"提示","确定清除全部缓存吗?",QMessageBox::Yes | QMessageBox::No);
        if(flag == QMessageBox::Yes){
            QByteArray *data = api.clearCacheAll();
            QJsonObject obj = QJsonDocument::fromJson(*data).object();
            if(obj.value("code").toInt() == 200){
                QMessageBox::information(0,"提示",obj.value("msg").toString());
            }
        }
    });

}

void CacheListManager::init()
{
    ui->tableWidget_cacheList_cacheList->setSortingEnabled(0);
    ui->tableWidget_cacheList_cacheList->sortByColumn(-1, Qt::AscendingOrder);
    ui->tableWidget_cacheList_cacheList->clear();
    QStringList columnHeader;
    columnHeader << "序号" << "缓存名称" << "备注" << "操作";
    ui->tableWidget_cacheList_cacheList->setColumnCount(columnHeader.size());
    ui->tableWidget_cacheList_cacheList->setHorizontalHeaderLabels(columnHeader);

    columnHeader.clear();
    columnHeader << "序号" << "缓存键名" << "操作";
    ui->tableWidget_cacheList_keyNameList->setColumnCount(columnHeader.size());
    ui->tableWidget_cacheList_keyNameList->setHorizontalHeaderLabels(columnHeader);

    initCacheListTable();
}

void CacheListManager::initKeyListTable(const QString &cacheName)
{
    ui->tableWidget_cacheList_keyNameList->setSortingEnabled(0);
    ui->tableWidget_cacheList_keyNameList->sortByColumn(-1, Qt::AscendingOrder);
    ui->tableWidget_cacheList_keyNameList->clear();
    QByteArray *data = api.getKeys(cacheName);
    QJsonArray arr = QJsonDocument::fromJson(*data).object().value("data").toArray();
    QStringList columnHeader;
    columnHeader << "序号" << "缓存键名" << "操作";
    ui->tableWidget_cacheList_keyNameList->setColumnCount(columnHeader.size());
    ui->tableWidget_cacheList_keyNameList->setHorizontalHeaderLabels(columnHeader);
    if(arr.isEmpty()){
        ui->tableWidget_cacheList_keyNameList->setRowCount(10);
        ui->tableWidget_cacheList_keyNameList->setShowGrid(0);
        ui->tableWidget_cacheList_keyNameList->setItem(3,1,new QTableWidgetItem("暂无数据"));
    }else{
        ui->tableWidget_cacheList_keyNameList->setShowGrid(1);
        ui->tableWidget_cacheList_keyNameList->setRowCount(arr.size());
        ui->tableWidget_cacheList_keyNameList->setColumnWidth(0,40);
        ui->tableWidget_cacheList_keyNameList->setColumnWidth(1,250);
        ui->tableWidget_cacheList_keyNameList->setColumnWidth(2,55);
        for (int i = 0; i < arr.size(); ++i) {
            ui->tableWidget_cacheList_keyNameList->setRowHeight(i,38);
            QString str = arr.at(i).toString();
            str = str.mid(str.indexOf(":") + 1);
            ui->tableWidget_cacheList_keyNameList->setItem(i,0,new QTableWidgetItem(QString::number(i+1)));
            ui->tableWidget_cacheList_keyNameList->setItem(i,1,new QTableWidgetItem(str));
            QWidget *tmp_widget = new QWidget();
            QHBoxLayout *tmp_layout = new QHBoxLayout();
            QPushButton *btnDelete = new QPushButton;
            connect(btnDelete,&QPushButton::clicked,this,[=](){
                api.clearCacheKey(cacheName,str);
                initCacheContent(cacheName,str);
                initKeyListTable(cacheName);
            });
            btnDelete->setText("🗑");
            btnDelete->setFixedSize(20,20);
            btnDelete->setCursor(Qt::PointingHandCursor);
            tmp_layout->addWidget(btnDelete);
            tmp_widget->setLayout(tmp_layout);
            tmp_layout->setContentsMargins(0,0,0,0);
            ui->tableWidget_cacheList_keyNameList->setCellWidget(i,2,tmp_widget);
        }
    }
    // 设置单元格内容居中对齐
    for (int row = 0; row < ui->tableWidget_cacheList_keyNameList->rowCount(); ++row) {
        for (int column = 0; column < ui->tableWidget_cacheList_keyNameList->columnCount(); ++column) {
            QTableWidgetItem* item = ui->tableWidget_cacheList_keyNameList->item(row, column);
            if (item) {
                item->setTextAlignment(Qt::AlignCenter);
            }
        }
    }
    ui->tableWidget_cacheList_keyNameList->setSortingEnabled(1);
}

void CacheListManager::initCacheContent(const QString &cacheName, const QString &cacheKeyName)
{
    QByteArray *data = api.getValue(cacheName,cacheKeyName);
    QJsonObject obj = QJsonDocument::fromJson(*data).object().value("data").toObject();
    ui->lineEdit_cacheName->setText(obj.value("cacheName").toString());
    QString cacheKey = obj.value("cacheKey").toString();
    cacheKey = cacheKey.startsWith(":") ? cacheKey.mid(1) : cacheKey;
    ui->lineEdit_cacheKeyName->setText(cacheKey);
    ui->textEdit_cacheContent->setText(obj.value("cacheValue").toString());
}

void CacheListManager::initCacheListTable()
{
    cacheList.clear();
    QByteArray *data = api.getNames();
    QJsonObject obj = QJsonDocument::fromJson(*data).object();
    QJsonArray arr = obj.value("data").toArray();
    for (int i = 0; i < arr.size(); ++i) {
        Cache cache = Cache::toCache(arr.at(i).toObject());
        cacheList.append(cache);
    }
    ui->tableWidget_cacheList_cacheList->setRowCount(cacheList.size());
    ui->tableWidget_cacheList_cacheList->setColumnWidth(0,40);
    ui->tableWidget_cacheList_cacheList->setColumnWidth(1,130);
    ui->tableWidget_cacheList_cacheList->setColumnWidth(2,130);
    ui->tableWidget_cacheList_cacheList->setColumnWidth(3,55);
    for (int i = 0; i < cacheList.size(); ++i) {
        ui->tableWidget_cacheList_cacheList->setRowHeight(i,38);
        ui->tableWidget_cacheList_cacheList->setItem(i,0,new QTableWidgetItem(QString::number(i+1)));
        QString str = cacheList.at(i).cacheName;
        str = str.endsWith(":") ? str.mid(0,str.indexOf(":")) : str;
        ui->tableWidget_cacheList_cacheList->setItem(i,1,new QTableWidgetItem(str));
        ui->tableWidget_cacheList_cacheList->setItem(i,2,new QTableWidgetItem(cacheList.at(i).remark));
        QWidget *tmp_widget = new QWidget();
        QHBoxLayout *tmp_layout = new QHBoxLayout();
        QPushButton *btnDelete = new QPushButton;
        connect(btnDelete,&QPushButton::clicked,this,[=](){
            api.clearCacheName(str);
            api.getKeys(str);
            initKeyListTable(cacheName);
        });
        btnDelete->setText("🗑");
        btnDelete->setCursor(Qt::PointingHandCursor);
        btnDelete->setFixedSize(20,20);
        tmp_layout->addWidget(btnDelete);
        tmp_widget->setLayout(tmp_layout);
        tmp_layout->setContentsMargins(0,0,0,0);
        ui->tableWidget_cacheList_cacheList->setCellWidget(i,3,tmp_widget);
    }
    // 设置单元格内容居中对齐
    for (int row = 0; row < ui->tableWidget_cacheList_cacheList->rowCount(); ++row) {
        for (int column = 0; column < ui->tableWidget_cacheList_cacheList->columnCount(); ++column) {
            QTableWidgetItem* item = ui->tableWidget_cacheList_cacheList->item(row, column);
            if (item) {
                item->setTextAlignment(Qt::AlignCenter);
            }
        }
    }
    ui->tableWidget_cacheList_cacheList->setSortingEnabled(1);
}

bool CacheListManager::eventFilter(QObject *obj, QEvent *event)
{
    if (event->type() == QEvent::MouseButtonPress){
        QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
        if(mouseEvent->button() == Qt::RightButton){
            if(obj == ui->tableWidget_cacheList_cacheList->viewport() || ui->tableWidget_cacheList_keyNameList->viewport()){
                if(ui->tableWidget_cacheList_cacheList->currentColumn() == 1 || ui->tableWidget_cacheList_cacheList->currentColumn() == 2
                    || ui->tableWidget_cacheList_keyNameList->currentColumn() == 1){
                    copyDlg = new QDialog;
                    copyDlg->setAttribute(Qt::WA_DeleteOnClose);
                    copyDlg->installEventFilter(this);
                    QVBoxLayout *l = new QVBoxLayout(copyDlg);
                    copyDlg->setWindowFlag(Qt::FramelessWindowHint);
                    QPushButton *btnCopy = new QPushButton;
                    btnCopy->setText("复制");
                    l->addWidget(btnCopy);
                    QPoint globalPos = static_cast<QWidget*>(obj)->mapToGlobal(mouseEvent->pos());
                    copyDlg->move(globalPos);
                    copyDlg->show();
                    connect(btnCopy,&QPushButton::clicked,this,[=](){
                        QClipboard *clipboard = QApplication::clipboard();
                        QTableWidgetItem *item = new QTableWidgetItem;
                        if(obj == ui->tableWidget_cacheList_cacheList->viewport()){
                            item = ui->tableWidget_cacheList_cacheList->currentItem();
                        }else{
                            item = ui->tableWidget_cacheList_keyNameList->currentItem();
                        }
                        clipboard->setText(item->text());
                        copyDlg->close();
                    });
                }

            }
        }
    }else if(event->type() == QEvent::Leave){
        if(obj == copyDlg){
            copyDlg->close();
        }
    }else if(event->type() == QEvent::ActivationChange){
        if(QApplication::activeWindow() != copyDlg){
            copyDlg->close();
        }
    }
    return QObject::eventFilter(obj, event);
}
